//
//  ProductDetail.m
//  cutter
//
//  Created by mac on 16/1/11.
//  Copyright © 2016年 e360. All rights reserved.
//
#import "MatchEdit.h"
#import "TMCutter.h"
#import "ProductCenterCtrl.h"
#import "MatchDetailCtrl.h"
#import "UserCenterPick.h"

@implementation MatchDetailCtrlCell
- (void)awakeFromNib{
    [super awakeFromNib];
    //
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTouch:)];
    [self.imageView addGestureRecognizer:tap];
    [tap setCancelsTouchesInView:NO];
}
- (void)tapTouch:(id)sender{
    if (self.hiddenInfo.constant!=0) {
        [self.hiddenInfo setConstant:0];
    }else{
        [self.hiddenInfo setConstant:-335];
    }
    [self updateConstraintsIfNeeded];
    //
    [UIView beginAnimations:nil context:nil];
    [self layoutIfNeeded];
    [UIView commitAnimations];
}
- (void)reset{
    [self setDetail:nil];
    [self.textView setText:@""];
    [self.dateView setText:@""];
    [self.priceView setText:@""];
    [self.authorView setText:@""];
    [self.attributeView setText:@""];
    [self.addFavorite setSelected:NO];
    [self.imageView.imageView setImage:nil];
    [self.addFavorite setUserInteractionEnabled:NO];
    [self.showList setUserInteractionEnabled:NO];
    //
    [self.hiddenInfo setConstant:0];
    [self updateConstraintsIfNeeded];
}
-(void)reloadData{
    if (self.data && self.detail==nil) {
        [self.data setValue:@"match" forKey:@"t"];
        //
        __weak MatchDetailCtrlCell *this = self;
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            id iid = [this.data objectForKey:@"id"];
            [this setDetail:[[AppData userMatchDetail:iid] firstObject]];
            dispatch_async(dispatch_get_main_queue(), ^{
                [this updateAll];
            });
        });
    }
}
-(void)reloadProduct:(ProductListCtrl*)ctrl{
    if (self.data && self.detail) {
        id products = [self.detail objectForKey:@"products"];
        if (products) {
            [ctrl setData:products];
            [ctrl reloadData];
            return;
        }
        //
        __weak ProductListCtrl *list = ctrl;
        __weak MatchDetailCtrlCell *this = self;
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            NSDictionary *json = [TMJSON parse:[this.detail objectForKey:@"json"]];
            if (json) {
                NSArray *items = [json objectForKey:@"identifier"];
                if (items.count > 0) {
                    NSMutableDictionary *census = [NSMutableDictionary dictionary];
                    for (id item in items) {
                        id key = [NSNumber numberWithInteger:[item integerValue]];
                        //
                        NSInteger value = [[census objectForKey:key] integerValue];
                        [census setValue:[NSNumber numberWithInteger:value + 1] forKey:key];
                    }
                    NSArray *products = [AppData productDetail:[census.allKeys componentsJoinedByString:@","]];
                    for (id product in products) {
                        id pid = [product objectForKey:@"id"];
                        id key = [NSNumber numberWithInteger:[pid integerValue]];
                        //
                        id temp = [census objectForKey:key];
                        [product setValue:[NSString stringWithFormat:@"%@",temp] forKey:@"count"];
                        [AppData productAttribute:product all:NO];
                    }
                    [this.detail setValue:products forKey:@"products"];
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [this reloadProduct:list];
            });
        });
    }
}
-(void)updateAll{
    [self.textView setText:[AppData objToString:[self.detail objectForKey:@"desc"] lable:nil]];
    [self.authorView setText:[NSString stringWithFormat:@"by %@", [AppData objToString:[self.detail objectForKey:@"author"] lable:nil]]];
    [self.dateView setText:[AppData dateToString:[self.detail objectForKey:@"postdate"] lable:nil]];
    [self.priceView setText:[AppData priceToString:[self.detail objectForKey:@"price"] lable:nil]];
    [AppData loadImage:[self.detail objectForKey:@"pic"] view:self.imageView.imageView];
    //
    NSString *string = @"";
    NSDictionary *classs = [self.detail objectForKey:@"class"];
    for (id item in classs) {
        id vals = [[item objectForKey:@"values"] componentsJoinedByString:@","];
        string = [string stringByAppendingFormat:@"%@：%@\n\n", [item objectForKey:@"name"], vals];
    }
    [self.attributeView setText:string];
    [self.addFavorite setEnabled:YES];
    //
    NSDictionary *client = [TMGlobal valueForKey:@"client"];
    id fav = [AppData userHaveFavorite:self.data client:client];
    if (fav) {
        [self.addFavorite setSelected:YES];
    }else{
        [self.addFavorite setSelected:NO];
    }
    [self.addFavorite setUserInteractionEnabled:YES];
    [self.showList setUserInteractionEnabled:YES];
}
@end

//产品详细
@implementation MatchDetailCtrl
- (void)viewDidLoad{
    [super viewDidLoad];
    [self.addScheme setHidden:NO];
    //
    if (self.type == 0) {
        for (NSLayoutConstraint *constraint in self.addScheme.constraints) {
            if (constraint.firstItem == self.addScheme) {
                if (constraint.firstAttribute == NSLayoutAttributeWidth) {
                    constraint.constant = 56;
                }
            }
        }
        [self.addScheme setImage:nil forState:UIControlStateNormal];
        [self.addScheme setImage:nil forState:UIControlStateHighlighted];
        [self.addScheme setTitle:@"编辑" forState:UIControlStateNormal];
    }
}
-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    //
    if (NO == CGRectEqualToRect(self.view.frame, self.frame)) {
        [self setFrame:self.view.frame];
        //
        NSInteger index = [self indexOfObject:self.data];
        if (index == NSNotFound) {
            if (self.data) {
                [self.source addObject:self.data];
            }
            index = 0;
        }
        //
        [self.collectionView reloadData];
        if ([self.source count] > 0) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
            [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
        }
    }
}
//
-(NSMutableArray *)source{
    if (_source == nil) {
        [self setSource:[NSMutableArray array]];
    }
    return _source;
}
-(NSInteger)indexOfObject:(id)object{
    for (NSInteger i=0;i<[self.source count];i++) {
        id temp = [self.source objectAtIndex:i];
        if ([[temp objectForKey:@"id"] isEqual:[self.data objectForKey:@"id"]]) {
            return i;
        }
    }
    return NSNotFound;
}
-(id)findCell:(UIView*)view{
    UIView *cell = view;
    while (cell) {
        if ([cell isKindOfClass:MatchDetailCtrlCell.class]) {
            return cell;
        }
        cell = [cell superview];
    }
    return nil;
}
-(id)currentCell{
    int page = roundf(self.collectionView.contentOffset.x / self.collectionView.frame.size.width);
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:page inSection:0];
    return [self.collectionView cellForItemAtIndexPath:indexPath];
}
//
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    MatchDetailCtrlCell *cell = [self currentCell];
    if (cell) {
        [self.titleView setText:[AppData objToString:[cell.data objectForKey:@"matchname"] lable:nil]];
        [cell reloadData];
    }
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (decelerate == NO) {
        [self scrollViewDidEndDecelerating:scrollView];
    }
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return [self.source count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    id item = [self.source objectAtIndex:indexPath.item];
    MatchDetailCtrlCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifler" forIndexPath:indexPath];
    if ([[collectionView indexPathsForVisibleItems] count] == 0) {
        [self.titleView setText:[AppData objToString:[item objectForKey:@"matchname"] lable:nil]];
        [cell setData:item];
        [cell reloadData];
    }else{
        [cell setData:item];
        [cell reset];
    }
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return collectionView.frame.size;
}
//
- (IBAction)exitTouch:(id)sender {
    if (self.navigationController) {
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        if (self.presentingViewController) {
            [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
        }else{
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    }
}
-(void)addFavoriteTouch:(UIButton*)sender{
    MatchDetailCtrlCell *cell = [self findCell:sender];
    if (cell) {
        NSDictionary *client = [TMGlobal valueForKey:@"client"];
        id fav = [AppData userHaveFavorite:cell.data client:client];
        if (fav) {
            [sender setSelected:NO];
        }else{
            [sender setSelected:YES];
        }
        //
        if (sender.selected) {
            if ([AppData userEditFavorite:self.data client:client]) {
                [TMAlert showAtView:self.view image:@"img_Prompt_Favorites_OK.png"];
            }
        }else{
            if ([AppData userDeleteFavorite:self.data client:client]) {
                [TMAlert showAtView:self.view image:@"img_Prompt_Favorites_Cancel.png"];
            }
        }
    }
}
-(BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender{
    if (sender == self.addScheme) {
        if (self.type == 1) {
            [self exitTouch:nil];
            if (self.onSelected) {
                MatchDetailCtrlCell *cell = [[self.collectionView visibleCells] firstObject];
                if (cell) {
                    self.onSelected(self, cell.detail);
                }
            }
            return NO;
        }
        return YES;
    }
    //
    if ([TMGlobal valueForKey:@"client"]) {
        if ([identifier isEqualToString:@"favoriteSegue"]) {
            [self addFavoriteTouch:sender];
            return NO;
        }
    }
    return YES;
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    __weak MatchDetailCtrl *this = self;
    if ([segue.destinationViewController isKindOfClass:UINavigationController.class]) {
        UINavigationController *ctrl = segue.destinationViewController;
        if ([[ctrl.viewControllers firstObject] isKindOfClass:UserCenterSelect.class]) {
            UserCenterSelect *root = [ctrl.viewControllers firstObject];
            [root setOnSelected:^(id target, id result){
                [this dismissViewControllerAnimated:YES completion:^{
                    if(result){
                        if ([segue.identifier isEqualToString:@"favoriteSegue"]) {
                            [this addFavoriteTouch:sender];
                        }
                    }
                }];
            }];
        }
    }
    //
    if ([segue.destinationViewController isKindOfClass:ProductListCtrl.class]) {
        MatchDetailCtrlCell *cell = [self findCell:sender];
        if (cell) {
            ProductListCtrl *ctrl = segue.destinationViewController;
            [cell reloadProduct:ctrl];
        }
    }
    //copy|edit
    if ([segue.destinationViewController isKindOfClass:MatchEdit.class]) {
        MatchDetailCtrlCell *cell = [self currentCell];
        if (cell) {
            NSMutableDictionary *copy = [NSMutableDictionary dictionaryWithDictionary:cell.detail];
            if (NO == [[[TMGlobal valueForKey:@"user"] objectForKey:@"id"] isEqual:[copy objectForKey:@"userid"]]) {
                [copy setValue:nil forKey:@"uuid"];
                [copy setValue:nil forKey:@"id"];
            }
            //
            __weak MatchEdit *ctrl = segue.destinationViewController;
            [ctrl setOnSelected:^(id target, id result){
                [ctrl dismissViewControllerAnimated:YES completion:nil];
            }];
            [ctrl import:copy];
        }
    }
}
@end